package com.junsi.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.junsi.bean.Approve;
import com.junsi.bean.Client;
import com.junsi.bean.Company;
import com.junsi.bean.Department;
import com.junsi.bean.Distribution;
import com.junsi.bean.Staff;
import com.junsi.service.CompanySerivce;
import com.junsi.service.DepartmentSerivce;
import com.junsi.service.DistributionSerivce;
import com.junsi.service.StaffSerivce;
import com.junsi.util.DownFile;
import com.junsi.util.FileUtil;
import com.junsi.util.InteractiveUtil;
import com.junsi.util.PageUtil;
import java.util.Map;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;

/**
 * 员工控制层
 * 
 * @author wkp
 *
 */
@Controller
@RequestMapping("/staff")
public class StaffController {

	@Autowired
	private StaffSerivce staffSerivce;

	@Autowired
	private DistributionSerivce distributionSerivce;

	@Autowired
	private DepartmentSerivce departmentSerivce;

	@Autowired
	private CompanySerivce companySerivce;

	/**
	 * 新增
	 * 
	 * @param staff
	 * @return
	 */
	@RequestMapping("/save")
	public void save(Staff staff, HttpServletResponse response) {
		if (staff != null && staff.getStaff_name() != null) {
			Staff staff2 = staffSerivce.findByUserName(staff.getStaff_phone());
			if (staff2 != null) {
				InteractiveUtil.WriteStringForHtml("手机号已存在", response);
				return;
			}
			boolean b = staffSerivce.save(staff);
			if (b) {
				InteractiveUtil.WriteStringForHtml("新增成功", response);
				return;
			}

		} else {
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}
	}

	/**
	 * 修改员工信息
	 * 
	 * @param staff
	 * @return
	 */
	@RequestMapping("/update")
	public void update(Staff staff, HttpServletResponse response) {

		if (staff != null && staff.getStaff_id() != null) {
			boolean reuslt = staffSerivce.update(staff);
			if (reuslt) {
				InteractiveUtil.WriteStringForHtml("修改成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("修改失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("修改失败", response);
		}
	}

	/**
	 * 前台修改员工信息
	 * 
	 * @param staff
	 * @return
	 */
	@RequestMapping("/qianupdate")
	public void update(Staff staff, HttpServletResponse response, HttpServletRequest request) {

		if (staff != null && staff.getStaff_id() != null) {
			boolean reuslt = staffSerivce.update(staff);
			if (reuslt) {
				if (staff.getStaff_userName() != null) {
					Staff staff2 = staffSerivce.findByUserName(staff.getStaff_userName());
					if (staff2 != null) {
						request.getSession().setAttribute("staff", staff2);
					}
				}
				InteractiveUtil.WriteStringForHtml("修改成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("修改失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("修改失败", response);
		}
	}

	/**
	 * 查询员工详情信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("findById")
	public void findById(Integer staff_id, HttpServletResponse response) {
		if (staff_id != null) {
			Staff staff = staffSerivce.findById(staff_id);
			if (staff != null) {
				InteractiveUtil.WriteBeanForHtml(staff, response);
				;
			} else {
				InteractiveUtil.WriteStringForHtml("失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("失败", response);
		}
	}

	/**
	 * 单ID删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteById")
	public void deleteById(Integer id, HttpServletResponse response) {
		if (id != null) {
			boolean reuslt = staffSerivce.delete(id);
			if (reuslt) {
				InteractiveUtil.WriteStringForHtml("删除成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("删除失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("删除失败", response);
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteManyId")
	@ResponseBody
	public void deleteManyId(String staff_id, HttpServletResponse response) {

		if (staff_id != null) {
			boolean reuslt = staffSerivce.deletes(staff_id);
			if (!reuslt) {
				InteractiveUtil.WriteStringForHtml("删除失败", response);
				return;
			}
		}

		InteractiveUtil.WriteStringForHtml("删除成功", response);
	}

	/**
	 * 根据部门查询所有下属员工
	 * 
	 * @param id
	 * @return JSON
	 */
	@RequestMapping("findByDepartment")
	public void findByDepartment(Integer id, PageUtil page, HttpServletResponse response) {

		if (id != null) {
			Integer number = staffSerivce.findByDepartmentNum(id);
			if (number != null) {
				page.setRowCount(number);
				List<Staff> list = staffSerivce.findByDepartment(id, page.getEndIndex(), page.getBeginIndex());
				if (list != null) {
					InteractiveUtil.WriteJsonForPage(list, page, response);
				} else {
					InteractiveUtil.WriteStringForHtml("失败", response);
				}
			}
		} else {
			InteractiveUtil.WriteStringForHtml("失败", response);
		}

	}

	/**
	 * 新增部门
	 * 
	 * @param department
	 * @return
	 */
	@RequestMapping("/saveDepartment")
	public void saveDepartment(Department department, HttpServletResponse response) {

		if (department != null && department.getDepartment_name() != null) {
			boolean reuslt = departmentSerivce.save(department);
			if (reuslt) {
				InteractiveUtil.WriteStringForHtml("新增成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("新增失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("新增失败", response);
		}

	}

	/**
	 * 进入部门/员工管理页面
	 * @return
	 */
	@RequestMapping("/selectTree")
	public ModelAndView selectTree(PageUtil page, HttpServletResponse response, HttpServletRequest request,String condition){
		ModelAndView modelAndView = new ModelAndView();
		HashMap<Company, HashMap<Department, List<Department>>> map = new HashMap<Company, HashMap<Department, List<Department>>>();
		List<Company> companies = companySerivce.findByAll();
		for (Company company : companies) {
			HashMap<Department, List<Department>> map2 = new HashMap<Department, List<Department>>();
			List<Department> departments = departmentSerivce.findByCompanyId(company.getCompany_id());
			for (Department department : departments) {
				if(department.getDepartment_departmentId() == null){
					List<Department> departments2 = departmentSerivce.findByTop(department.getDepartment_id());
					map2.put(department, departments2);
				}
			}
			map.put(company,  map2);
		}
		List<Staff> staffs = staffSerivce.findByAll();
		List<Department> departments = departmentSerivce.findByAll();
		modelAndView.addObject("listStaff", staffs);
		modelAndView.addObject("map", map);
		modelAndView.addObject("departments", departments);
		page.setPageSize(5);
		Integer count =null;
		if(condition!=null && !"".equals(condition)) {
			count=staffSerivce.findAllCountCondition(condition.trim());
			modelAndView.addObject("condition", condition);
		}else {
			count=staffSerivce.findAllCount();
		}
		page.setRowCount(count);
		modelAndView.setViewName("forward:/html/bumenyonghuguanli.jsp");//--------------------------
		modelAndView.addObject("PageCount", page.getPageCount());
		modelAndView.addObject("PageNum", page.getPageNum());
		return modelAndView;
	}

	/**
	 * 进入部门/员工管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/selectAll")
	public void selectAll(PageUtil page, HttpServletResponse response, String condition, HttpServletRequest request) {
		Integer count=null;
		List<Staff> staffs=null;
		if(condition!=null && !"".equals(condition)) {
			page.setPageSize(5);
			count = staffSerivce.findAllCountCondition(condition.trim());
			page.setRowCount(count);
			staffs = staffSerivce.findAllPageCondition(page,condition.trim());
		}else {
			page.setPageSize(5);
			 count = staffSerivce.findAllCount();
			page.setRowCount(count);
		    staffs = staffSerivce.findAllPage(page);
		}
		List<Department> departments = departmentSerivce.findByAll();
		List<Map<String, String>> array = new ArrayList<Map<String, String>>();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		for (Staff staffArray : staffs) {
		Map<String, String> map = new HashMap<String, String>();
		 map.put("staff_id", staffArray.getStaff_id().toString());//id
		 map.put("staff_name", staffArray.getStaff_name());//姓名
		 map.put("staff_phone", staffArray.getStaff_phone()==null?"":staffArray.getStaff_phone());//手机号
		 map.put("staff_email", staffArray.getStaff_email()==null?"":staffArray.getStaff_email());//邮箱
		 map.put("staff_sex", staffArray.getStaff_sex()==null?"":staffArray.getStaff_sex());//性别
		 map.put("staff_job", staffArray.getStaff_job()==null?"":staffArray.getStaff_job());//职位
		 map.put("staff_userName", staffArray.getStaff_userName()==null?"":staffArray.getStaff_userName());//帐号
		 
		 for(Department department:departments) {
			 String departmentCount=department.getDepartment_id().toString();
			 if(staffArray.getStaff_departmentId()!=null) {
				String staffDepartmen=staffArray.getStaff_departmentId().toString();
			 if(staffDepartmen.equals(departmentCount==null?"":departmentCount)) {
				 map.put("department_name", department.getDepartment_name()==null?"":department.getDepartment_name());//部门
				 map.put("department_nameID", department.getDepartment_id().toString());
			 }
			 }
		 }
		 if(staffArray.getStaff_entryDate()!=null){
			 String entryDate=simpleDateFormat.format(staffArray.getStaff_entryDate());
			 map.put("staff_entryDate", entryDate);//入职日期
		 }
		 array.add(map);
		}
		response.setContentType("text/json; charset=UTF-8");
		InteractiveUtil.WriteJsonForPage(array, page, response);
	}

	/**
	 * 新增部门页面，根据公司ID查询部门信息
	 * 
	 * @param department_companyId
	 * @param response
	 */
	@RequestMapping(value = "/saveDepartmentPage")
	public void saveDepartmentPage(Integer department_companyId, HttpServletResponse response) {
		if (department_companyId != null) {
			List<Department> departments = departmentSerivce.findByCompanyId(department_companyId);
			InteractiveUtil.WriteJsonForHtml(departments, response);
		}
		InteractiveUtil.WriteStringForHtml("失败", response);
	}

	/**
	 * 根据ID查询部门
	 * 
	 * @param department_id
	 * @param response
	 */
	@RequestMapping(value = "findDepartmentId")
	public void findDepartmentId(Integer department_id, HttpServletResponse response) {

		if (department_id != null) {
			Department department = departmentSerivce.findById(department_id);
			if (department != null && department.getDepartment_name() != null) {
				InteractiveUtil.WriteBeanForHtml(department, response);
				;
			} else {
				InteractiveUtil.WriteStringForHtml("失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("失败", response);
		}
	}

	/**
	 * 修改部门信息
	 * 
	 * @param department
	 * @param response
	 */
	@RequestMapping(value = "/updateDepartment")
	public void updateDepartment(Department department, HttpServletResponse response) {
		if (department.getDepartment_id() != null) {
			boolean b = departmentSerivce.update(department);
			if (b) {
				InteractiveUtil.WriteStringForHtml("修改成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("删除失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("删除失败", response);
		}
	}

	/**
	 * 删除部门
	 * 
	 * @param department_id
	 * @param response
	 */
	@RequestMapping(value = "/deleteDepartment")
	public void deleteDepartment(Integer department_id, HttpServletResponse response) {
		if (department_id != null) {
			boolean b = departmentSerivce.delete(department_id);
			if (b) {
				InteractiveUtil.WriteStringForHtml("删除成功", response);
			} else {
				InteractiveUtil.WriteStringForHtml("删除失败", response);
			}
		} else {
			InteractiveUtil.WriteStringForHtml("删除失败", response);
		}
	}

	/**
	 * 根据部门ID查询员工信息
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "/findByDepId")
	public void findByDepId(Integer id, HttpServletResponse response) {
		if (id != null) {
			List<Staff> staffs = staffSerivce.findByDepId(id);
			InteractiveUtil.WriteJsonForHtml(staffs, response);
		} else {
			InteractiveUtil.WriteStringForHtml("查询失败", response);
		}
	}

	/**
	 * 查询所有部门
	 * 
	 * @param response
	 */
	@RequestMapping(value = "/findAllDeps")
	public void findAllDeps(HttpServletResponse response) {
		List<Department> departments = departmentSerivce.findByAll();
		InteractiveUtil.WriteJsonForHtml(departments, response);
	}

	/**
	 * 多条件查询
	 * 
	 * @param selectWhere
	 * @param response
	 */
	@RequestMapping("searchBox")
	public void searchBox(String selectWhere, HttpServletResponse response) {
		if (selectWhere == null) {
			InteractiveUtil.WriteStringForHtml("条件有误", response);
		}
		List<Staff> staffs = staffSerivce.findSelectWhere(selectWhere);
		InteractiveUtil.WriteJsonForHtml(staffs, response);

	}

	public List<String> exiclUtilByStaff(String path) {

		// 直接读取文件:
		String filePath = path;
		File file = new File(filePath);
		InputStream is;
		XSSFSheet sheetMain;
		List<String> strings = new ArrayList<>();
		try {
			is = new FileInputStream(file);
			XSSFWorkbook wb = new XSSFWorkbook(is);
			// 读取第一个Sheet
			sheetMain = wb.getSheetAt(0);
			is.close();

			// 总共的行数
			int rowLens = sheetMain.getLastRowNum();
			int colLens = 7;
			int errCnt = 0;
			XSSFRow row = null;
			XSSFCell cell = null;
			String content = "";

			List<Department> departments = departmentSerivce.findByAll();
			exc: for (int rowCount = 1; rowCount <= rowLens; rowCount++) {
				Staff staff = new Staff();
				System.out.println("读取行：" + rowCount);
				row = sheetMain.getRow(rowCount);
				if (row != null) {
					boolean a = true;
					cc: for (int colCount = 0; colCount < colLens; colCount++) {
						cell = row.getCell(colCount);
						content = getCellValue(cell).trim();

						if (colCount == 0) {

							if (content == "") {
								a = false;
								strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：为空保存失败");
								break cc;
							} else {
								staff.setStaff_name(content);
							}

						} else if (colCount == 1) {
							if (content == "") {
								a = false;
								strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：为空保存失败");
								break cc;
							} else {
								Staff staff2 = staffSerivce.findByUserName(content);
								if (staff2 == null) {
									staff.setStaff_phone(content);
								} else {
									strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：手机号已存在保存失败");
								}
							}
						} else if (colCount == 2) {
							if (content == "") {
								a = false;
								strings.add("行 ：" + rowCount + "；列 ：" + colCount + "的内容：为空保存失败");
								break cc;
							} else {
								staff.setStaff_password(content);
							}
						} else if (colCount == 3) {
							if (content == "") {
							} else {
								staff.setStaff_email(content);
							}
						} else if (colCount == 4) {
							if (content == "") {
							} else {
								staff.setStaff_job(content);
							}
						} else if (colCount == 5) {
							if (content == "") {
							} else {
								int deid = 0;
								for (Department department : departments) {
									if (content.equals(department.getDepartment_name())) {
										staff.setStaff_departmentId(department.getDepartment_id());
										deid++;
									}
								}
								if (deid == 0) {
									strings.add("行 ：" + rowCount + "的部门不存在");
								}
							}
						} else if (colCount == 6) {
							if (content == "") {
							} else {
								staff.setStaff_sex(content);
							}
						} else if (colCount == 7) {
							if (content == "") {
							} else {
								Date date = new Date(content);
								staff.setStaff_entryDate(date);
							}
						}

					}

					if (a) {
						boolean b = staffSerivce.save(staff);
						if (b) {
							Distribution distribution = new Distribution();
							distribution.setDistribution_roleId(5);
							distribution.setDistribution_staffId(staff.getStaff_id());
							boolean reuslt = distributionSerivce.save(distribution);
							if (reuslt) {
								strings.add("行 ：" + rowCount + "的内容：保存成功");
							} else {
								staffSerivce.delete(distribution.getDistribution_id());
								strings.add("行 ：" + rowCount + "的内容：保存失败");
							}
						} else {
							strings.add("行 ：" + rowCount + "的内容：保存失败");
						}
					}

				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strings;
	}

	public static String getCellValue(XSSFCell cell) {
		if (cell != null) {
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_BLANK:
				return "";
			case XSSFCell.CELL_TYPE_NUMERIC:
				String strValue = String.valueOf(cell.getNumericCellValue());
				if (strValue != null && strValue.indexOf(".") != -1 && strValue.indexOf("E") != -1) {
					try {
						return new DecimalFormat().parse(strValue).toString();
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else {
					if (strValue.endsWith(".0")) {
						return strValue.substring(0, strValue.indexOf(".0"));
					} else {
						return strValue;
					}
				}
			case XSSFCell.CELL_TYPE_STRING:
				return (cell.getStringCellValue() + "").trim();
			case XSSFCell.CELL_TYPE_FORMULA:
				return (cell.getCellFormula() + "").trim();
			case XSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case XSSFCell.CELL_TYPE_ERROR:
				return cell.getErrorCellValue() + "";
			}
		}
		return "";
	}

	/**
	 * 员工批量导入
	 * 
	 * @param file
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/staffImput")
	public void staffImput(@RequestParam("file") CommonsMultipartFile file, HttpServletResponse response)
			throws IOException {
		if (!file.isEmpty()) {
			String picture1 = FileUtil.fileUploe(file);
			if (!"图片上传失败".equals(picture1)) {
				List<String> strings = exiclUtilByStaff(picture1);
				if (strings.size() != 0) {
					InteractiveUtil.WriteJsonForHtml(strings, response);
					return;
				}
			}
		}
		InteractiveUtil.WriteStringForHtml("批量导入失败，请检查文件格式", response);
	}

	/**
	 * 新增公司
	 * 
	 * @param company
	 * @param response
	 */
	@RequestMapping("saveCompany")
	public ModelAndView saveCompany(Company company, HttpServletResponse response) {
		companySerivce.save(company);
		return new ModelAndView("redirect:/staff/selectTree.action");
	}

	/**
	 * 修改部门
	 * 
	 * @param company
	 * @param response
	 */
	@RequestMapping(value = "updateCompany")
	public void updateCompany(Company company, HttpServletResponse response) {
		boolean b = companySerivce.update(company);
		if (b) {
			InteractiveUtil.WriteStringForHtml("修改成功", response);
		} else {
			InteractiveUtil.WriteStringForHtml("修改失败", response);
		}
	}

	/**
	 * 删除客户
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "deleteCompany")
	public void delete(Integer id, HttpServletResponse response) {
		boolean b = companySerivce.delete(id);
		if (b) {
			InteractiveUtil.WriteStringForHtml("删除成功", response);
		} else {
			InteractiveUtil.WriteStringForHtml("删除失败", response);
		}
	}

	@RequestMapping("/downFile")
	public void downFile(HttpServletResponse response, HttpServletRequest request) throws IOException {

		DownFile.download(DownFile.PATH + "file/staff.xlsx", response, request);

	}

}
